package com.laker.admin.common;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import org.apache.commons.lang.StringUtils;

import java.util.Iterator;
import java.util.List;

@Data
public class SearchModel<T> {

    private Integer pageIndex;
    private Integer pageSize;
    private List<Field> fields;
    private String orderField;
    private String isAsc;
    private String modelName;

    public IPage<T> getPage() {
        IPage<T> page = new Page<>(pageIndex, pageSize);
        return page;

    }

    public QueryWrapper<T> getQueryModel() {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        if(this.fields!=null){
            for (Iterator iter = this.fields.iterator(); iter.hasNext(); ) {
                Field field = (Field) iter.next();
                String underlineCase = StrUtil.toUnderlineCase(field.getName());
                switch (field.getQueryMethod()) {
                    case eq:
                        queryWrapper.eq(true, underlineCase, field.getValue());
                        break;
                    case like:
                        queryWrapper.like(true, underlineCase, field.getValue());
                        break;
                    case in:
                        String value= (String)field.getValue();
                        String[] split = value.split(",");
                        queryWrapper.in(true, underlineCase,split );
                        break;
                    case ne://不等于<>
                        queryWrapper.ne(true, underlineCase, field.getValue());
                        break;
                    case gt://大于>
                        queryWrapper.gt(true, underlineCase, field.getValue());
                        break;
                    case ge://大于等于>=
                        queryWrapper.ge(true, underlineCase, field.getValue());
                        break;
                    case lt://小于<
                        queryWrapper.lt(true, underlineCase, field.getValue());
                        break;
                    case le://小于等于<=
                        queryWrapper.le(true, underlineCase, field.getValue());
                        break;
                }
            }
        }

        if (StringUtils.isNotBlank(orderField)) {
            String underlineCase = StrUtil.toUnderlineCase(orderField);
            Boolean isAscChange = Boolean.valueOf(isAsc);
            queryWrapper.orderBy(true, isAscChange, underlineCase);
        }
        return queryWrapper;
    }
}